package cn.cutie.clot.gateway.web.handler;

import cn.cutie.clot.gateway.filter.GatewayFilter;
import cn.cutie.clot.gateway.plugin.DefaultGatewayPluginChain;
import cn.cutie.clot.gateway.plugin.GatewayPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Description:
 * WebHandler：spring自己串连
 * @Author: Cutie
 * @CreateDate: 2024/6/4 20:26
 * @Version: 0.0.1
 */
@Component("gatewayWebHandler")
public class GatewayWebHandler implements WebHandler {

    // spring会找到符合这个类型的所有的bean，添加到这个plugins列表中
    @Autowired
    List<GatewayPlugin> plugins;

    @Autowired
    List<GatewayFilter> filters;

    // flatMap 惰性求值
    // just 立马求值
    // mono和flux默认都是惰性求值的
    // 下面的可以一行flux return
    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {
        System.out.println("===>>> Clot Gateway web handler ...");
        if (plugins == null || plugins.isEmpty()){
            String mock = """
                {"result": "no plugin"}
                """;
            return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(mock.getBytes())));
        }

        for (GatewayFilter filter:filters) {
            filter.filter(exchange);
        }

        return new DefaultGatewayPluginChain(plugins).handle(exchange);

//        for (GatewayPlugin plugin: plugins) {
//            if (plugin.support(exchange)){
//                return plugin.handle(exchange);
//            }
//        }

//        String mock = """
//                {"result": "no supported plugin"}
//                """;
//        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(mock.getBytes())));
    }
}
